package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author : [wangtao]
 * @className : UserController
 * @description : []
 * @createTime : [2022/10/13 11:02]
 * @updateTime : [2022/10/13 11:02]
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R sendMsq(@RequestBody UserDto userDto, HttpSession session){
       log.info("userDto:{}",userDto);
        String phone = userDto.getPhone();
        if(StringUtils.isEmpty(phone)){
            return R.error("短信发送失败,重新输入电话号码");
        }
        //随机生成4位验证码
        String code= ValidateCodeUtils.generateValidateCode(4).toString();

     log.info("sendMsg.code={}",code);

        //调用阿里云服务API 发送短信
        SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
        session.setAttribute(phone,code);
        return R.success("验证码短信发送成功");
    }
    @PostMapping("/login")
    public R login(@RequestBody UserDto userDto, HttpSession session){
        log.info("userDto:{}",userDto);
        //获取手机号
        String phone = userDto.getPhone();
        //从session中,获取系统生成的验证码,
        Object Code = session.getAttribute(phone);
        log.info("Code:{}",Code);
        //进行验证码验证,session中的code值与用户提交的code进行匹配
        if(Code!=null&&Code.equals(userDto.getCode())){
            //检验user表中是否该用户信息,
            LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<>();
            lqw.eq(StringUtils.isNotEmpty(phone),User::getPhone,phone);
            User user = userService.getOne(lqw);
            //user表中 无用户信息则向用户表中添加用户
            if(user==null){
                user=new  User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);

            }
            //将用户id存入session 以备过滤器查验
            session.setAttribute("userId",user.getId());
            return R.success("登陆成功");
        }
   return R.error("登录失败");

    }
}
